package com.tusuo.stds.ui.rank;

import android.content.Context;

import com.hannesdorfmann.mosby.mvp.MvpBasePresenter;
import com.tusuo.stds.MyApp;
import com.tusuo.stds.R;
import com.tusuo.stds.di.DaggerScope;
import com.tusuo.stds.di.Injector;
import com.tusuo.stds.rest.ApiHelper;
import com.tusuo.stds.rest.RankList;
import com.tusuo.stds.util.Utils;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import rx.Subscriber;
import timber.log.Timber;

/**
 * @author J.Huang
 * @version 1.0
 *
 */
@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(RankPresenter.class)
class RankPresenter extends MvpBasePresenter<RankView> {

    @Inject
    ApiHelper mApiHelper;

    private Context mContext;
    private String mErrMsgServer;

    private Subscriber<RankList> mGetRankSubscriber = null;

    private int mType;
    private int mId;

    RankPresenter(Context context, int type, int id) {
        mContext = context;
        mErrMsgServer = mContext.getResources().getString(R.string.err_msg_server);
        mType = type;
        mId = id;

        Injector.initRankPresenterComponent().inject(this);
    }

    @Override
    public void attachView(RankView view) {
        super.attachView(view);

        mGetRankSubscriber = new GetRankSubscriber();

        // 1: scene; 2: module
        if (mType == 1) {
            mApiHelper.getSceneRank(mGetRankSubscriber, mId);
        } else if (mType == 2) {
            mApiHelper.getModuleRank(mGetRankSubscriber, mId);
        }
    }

    @Override
    public void detachView(boolean retainInstance) {
        if (mGetRankSubscriber != null) {
            mGetRankSubscriber.unsubscribe();
            mGetRankSubscriber = null;
        }
        super.detachView(retainInstance);
    }

    private class GetRankSubscriber extends Subscriber<RankList> {
        @Override
        public void onCompleted() {}

        @Override
        public void onError(Throwable e) {
            Timber.d(e.toString());
            Utils.UI.showToastShort(mErrMsgServer);
        }

        @Override
        public void onNext(final RankList list) {
            if (list.checkState(mContext) && getView() != null) {
                getView().setRankList(list);
            }
        }
    }
}
